package handler

import (
	"context"
	"evaluation/api/request"
	"evaluation/consts"
	"evaluation/global"
	"evaluation/internal/model"
	"evaluation/pkg"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

func RegisterUser(c *gin.Context) {
	var req request.RegisterUserForm
	var user model.User

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "验证失败",
			"data":    "",
		})
		return
	}

	user.Mobile = req.Mobile
	err := user.LoginUser()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "注册失败",
			"data":    "",
		})
		return
	}

	if user.Id > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "手机号已被使用",
			"data":    "",
		})
		return
	}

	user.Password = pkg.Md5(req.Password)
	user.Name = req.Name
	err = user.RegisterUser()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "注册失败",
			"data":    "",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "注册成功",
		"data":    user.Name,
	})
}

func LoginUser(c *gin.Context) {

	var req request.LoginUserForm
	var user model.User

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "验证失败",
			"data":    "",
		})
		return
	}

	user.Mobile = req.Mobile
	err := user.LoginUser()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "登陆失败",
			"data":    "",
		})
		return
	}

	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "账号或密码错误",
			"data":    "",
		})
		return
	}

	if user.Password != pkg.Md5(req.Password) {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "账号或密码错误",
			"data":    "",
		})
		return
	}

	token := pkg.CreatedJwtToken(user.Id, 3*(24*time.Hour), consts.JWT_KEY)
	global.RDB.Set(context.Background(), fmt.Sprintf("token:%d", token), user.Id, 3*(24*time.Hour))

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "登陆成功",
		"data":    token,
	})

}

func BannedUser(c *gin.Context) {
	ui := c.GetUint("token")
	var user model.User

	user.Id = uint32(ui)
	user.Status = 3
	err := user.BannedUser()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "封禁失败",
			"data":    "",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "封禁成功",
		"data":    user.Status,
	})

}

func GoOutUser(c *gin.Context) {

	token := c.GetHeader("token")

	global.RDB.Del(context.Background(), fmt.Sprintf("token:%d", token))
}
